//
//  JSONCodable.swift
//  ObjcCodable
//
//  Created by chenbo on 2025/2/10.
//

import Foundation

typealias JSONCodable = JSONDecodable & JSONEncodable

/// JSON编码扩展协议
protocol JSONEncodable: Codable {

    /// 从Encodable模型生成字典
    var jsonObject: Any? { get }
    
    /// 从Encodable模型生成JSON字符串
    var jsonString: String? { get }
    
}

extension JSONEncodable {
    
    var jsonObject: Any? {
        return JSONEncodableUtil.jsonObject(self)
    }
    
    var jsonString: String? {
        return JSONEncodableUtil.jsonString(self)
    }
}

extension Array: JSONEncodable where Element: JSONEncodable {}

/// JSON解码扩展协议
protocol JSONDecodable: Decodable {
    
    /// 从字典创建实例模型
    static func instance(jsonObject: Any?) -> Self?
    
    /// 从JSON字符串生成实例模型
    static func instance(jsonString: String?) -> Self?
}

extension JSONDecodable {
    
    static func instance(jsonObject: Any?) -> Self? {
        return JSONDecodableUtil.decode(jsonObject: jsonObject)
    }

    static func instance(jsonString: String?) -> Self? {
        return JSONDecodableUtil.decode(jsonString: jsonString)
    }
}

extension Array: JSONDecodable where Element: JSONDecodable {}
